package com.terren.spider.core.html.configuration.strategy.basic.impl;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import com.terren.spider.core.html.configuration.strategy.basic.IBasicStrategy;
import com.terren.spider.util.common.LogUtil;

public class BlackListStrategyImpl implements IBasicStrategy {
    private Set<String> needIgnoreDomainList = Sets.newConcurrentHashSet();

    @Override
    public boolean requiredToHandle(String host) {
    	boolean need = !needIgnoreDomainList.contains(host);
    	if (need) {
    		LogUtil.logger.info("site [" + host+"]  is required to handle");
		}
        return need;
    }

    public void add2BlackList(String host) {
        // check host pattern
        if (StringUtils.startsWithIgnoreCase(host, "http") || StringUtils.contains(host, ":")
                || StringUtils.contains(host, "/")) {
            throw new IllegalArgumentException(host + " 不是一个合法域名,请注意填写的是域名,不是URL");
        }
        needIgnoreDomainList.add(host);
    }

    public void addAllHost(String configRule) {
        if (StringUtils.isEmpty(configRule)) {
        	LogUtil.logger.warn("the abuyun proxy blacklist is null");
            return;
        }
        for (String domain : Splitter.on(",").omitEmptyStrings().trimResults().split(configRule)) {
            add2BlackList(domain);
        }
    }

    public void removeFromBackList(String host) {
        needIgnoreDomainList.remove(host);
    }
}